<template>
    <div class="box">
        <!-- <div class="form"> -->
        <el-form ref="ruleFormRef" :model="user" :rules="rules" label-width="120px" class="demo-ruleForm" status-icon>
            <el-form-item label="用户名" prop="username">
                <el-input v-model="user.username" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="user.password" type="password" />
            </el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)">登录</el-button>
        </el-form>
        <!-- </div> -->
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import type { FormInstance, FormRules } from 'element-plus'
// 提示弹窗
import { ElMessage } from 'element-plus'
// 引入接口
import { userLogin } from '@/request/app'
const ruleFormRef = ref<FormInstance>()
// 定义表单初始数据
let user = ref({
    username: '',
    password: ''
})
let router = useRouter()
const rules = reactive<FormRules>({
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 8, message: '长度为3到8位', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 4, max: 10, message: '长度为4到10', trigger: 'blur' },
    ],
})
// 置空事件
let reset = () => {
    user.value = {
        username: '',
        password: ''
    }
}
// 仓库
const store = useStore()
// 登录事件
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log('登录成功')
            console.log(user, '表单');
            // 调用登录接口
            userLogin(user.value)
                .then(res => {
                    console.log(res, '登录成功');
                    if (res.code == 200) {
                        // 将用户信息存入仓库
                        store.commit('USER_LOGIN', res.list)
                        ElMessage.success(res.msg)
                        // 登录成功后清空表单
                        reset()
                        // 跳转到首页
                        router.push('/index')
                    } else {
                        ElMessage.error(res.msg)
                    }
                })

        } else {
            console.log('登录失败', fields)
        }
    })
}

</script>
<style scoped>
.box {
    width: 100vw;
    height: 100vh;
    background-color: antiquewhite;
}

.demo-ruleForm {
    width: 400px;
    height: 200px;
    background-color: aqua;
    text-align: center;
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    margin: auto;
    padding-top: 40px;
    padding-right: 60px;
    box-sizing: border-box;
}
</style>
